package com.ruoyi.project.app.interfaces;

import com.alibaba.fastjson.JSON;
import com.ruoyi.project.app.util.StringUtil;
import com.ruoyi.project.app.util.XException;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 旷视API
 */
public interface FaceRequestInterface extends FaceApiInterface, HttpInterface {
    String cacheKey = "cacheKeyToken_#_";
    String verifyUrl = "https://api.megvii.com/faceid/v3/sdk/verify";
    String tokenUrl = "https://api.megvii.com/faceid/v3/sdk/get_biz_token";

    /**
     * 所获得的数据进行上传，并获取活体验证、人脸比对、攻击防范等结果信息
     *
     * @param token token参数
     * @param data  二进制文件
     * @return 验证结果
     * @throws Exception 运行异常
     */
    default String requestVerifyUrl(String token, byte[] data) throws Exception {
        Map<String, String> params = new HashMap<>();
        params.put("sign", createSign());
        params.put("sign_version", signVersion);
        params.put("biz_token", token);
        String result = doPostFile(verifyUrl, params, "meglive_data.txt", "meglive_data", data, "UTF-8");
        if (result != null && !"".equals(result)) {
            System.out.println("result=" + result);
            //        String resultDome = "{" +
//                "   \"time_used\":1448," +
//                "   \"verification\":{" +
//                "      \"idcard\":{" +
//                "         \"confidence\":86.63057," +
//                "         \"thresholds\":{" +
//                "            \"1e-3\":62.168713," +
//                "            \"1e-5\":74.39926," +
//                "            \"1e-4\":69.31534," +
//                "            \"1e-6\":78.038055" +
//                "         }" +
//                "      }" +
//                "   }," +
//                "   \"attack_result\":{" +
//                "      \"score\":0.26," +
//                "      \"threshold\":0.5," +
//                "      \"result\":false" +
//                "   }," +
//                "   \"request_id\":\"1531397565,39b19451-393c-4fc4-8fae-6dc74b2b00d7\"," +
//                "   \"images\":{" +
//                "      \"image_best\":\"xxxxxxxxxxx\"" +
//                "   }," +
//                "   \"biz_no\":\"\"," +
//                "   \"result_message\":\"SUCCESS\"," +
//                "   \"result_code\":1000" +
//                "}";
            Map map = JSON.parseObject(result, Map.class);
            Object resultMessage = map.get("result_message");
            if (resultMessage != null && "SUCCESS".equals(String.valueOf(resultMessage))) {
                return result;
            }
        }
        throw new XException("验证失败！");
    }

    /**
     * 获取人脸识别的token
     *
     * @param username 用户名称
     * @param idCard   用户身份证号
     * @return token
     */
    default Object requestVerifyToken(String username, String idCard) throws Exception {
        if (StringUtils.isBlank(username)) throw new XException("未实名认证！");
        if (StringUtils.isBlank(idCard)) throw new XException("未实名认证！");
        OkHttpClient client = new OkHttpClient();
        RequestBody multipartBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("sign", createSign())
                .addFormDataPart("sign_version", signVersion)
                .addFormDataPart("liveness_type", "meglive")
                .addFormDataPart("comparison_type", "1")
                .addFormDataPart("idcard_name", username)
                .addFormDataPart("idcard_number", idCard)
                .build();
        Request request = new Request.Builder().url(tokenUrl)
                .addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30)")
                .header("Content-Type", "text/html; charset=utf-8;")
                .post(multipartBody)//传参数、文件或者混合，改一下就行请求体就行
                .build();

        Response response = client.newCall(request).execute();
        ResponseBody body = response.body();
        if (body != null) {
            String result = body.string();//获取字符串数据
            System.out.println("result=" + result);
            if (response.code() == 200) {
                if (result != null && !"".equals(result)) {
                    Map map = JSON.parseObject(result, Map.class);
                    Object bizToken = map.get("biz_token");
                    if (bizToken != null) {
                        return bizToken;
                    }
                }
            }
        }
        throw new XException("获取失败！");
    }

    /**
     * 所获得的数据进行上传，并获取活体验证、人脸比对、攻击防范等结果信息
     *
     * @param token token参数
     * @param data  二进制文件
     * @return 验证结果
     * @throws Exception 运行异常
     */
    default Object requestVerifyUrlOk(String token, byte[] data) throws Exception {
        OkHttpClient client = new OkHttpClient();
        MediaType mediaType = MediaType.parse("multipart/form-data; charset=utf-8");
        RequestBody multipartBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("sign", createSign())
                .addFormDataPart("sign_version", signVersion)
                .addFormDataPart("biz_token", token)
                .addFormDataPart("meglive_data", "meglive_data", RequestBody.create(mediaType, data))
                .build();
        Request request = new Request.Builder().url(verifyUrl)
                .addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30)")
                .header("Content-Type", "text/html; charset=utf-8;")
                .post(multipartBody)//传参数、文件或者混合，改一下就行请求体就行
                .build();

        Response response = client.newCall(request).execute();
        ResponseBody body = response.body();
        System.out.println("code=" + response.code());
        if (body != null) {
            String result = body.string();//获取字符串数据
            System.out.println("result=" + result);
            if (response.code() == 200) {
                if (result != null && !"".equals(result)) {
                    Map map = JSON.parseObject(result, Map.class);
                    Object resultMessage = map.get("result_message");
                    if (resultMessage != null && "SUCCESS".equals(String.valueOf(resultMessage))) {
                        return map;
                    }
                }
            }
        }
        throw new XException("验证失败！");
    }
}
